package com.example.servlet.user;

import com.example.entity.Flight;
import com.example.entity.User;
import com.example.service.FlightService;
import com.example.service.impl.FlightServiceImpl;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@WebServlet("/user_index")
public class uIndex1Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try  (SqlSession sqlSession = MybatisUtil.getSession()) {
            User user = (User) req.getSession().getAttribute("user");
            Context context = new Context();
            FlightService service = new FlightServiceImpl(sqlSession);
            List<String> top4ArrivalCities = service.getTop4ArrivalCities();
            List<String> top4DepartureCities = service.getTop4DepartureCities();
            List<String> From = new ArrayList<>();
            List<String> To = new ArrayList<>();
            int city_count=0;
            Random random = new Random();
            Set<String> pairSet = new HashSet<>();
            while(true){
                int index1 = random.nextInt(4);
                int index2 = random.nextInt(4);
                String from = top4DepartureCities.get(index1);
                String to = top4ArrivalCities.get(index2);
                String pair = from + "->" + to;
                if(from.equals(to)) continue;
                if (!pairSet.contains(pair)) {
                    pairSet.add(pair);
                    From.add(from);
                    To.add(to);
                    city_count++;
                }
                if(city_count>=3) break;
            }
            LocalDate today = LocalDate.now();  // 获取当前日期
            LocalDate tomorrow = today.plusDays(1);  // 获取明天日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");  // 定义格式
            String tomorrowStr = tomorrow.format(formatter);  // 格式化输出
            List<Flight> flights = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                String from = From.get(i);
                String to = To.get(i);
                flights.add(service.searchCheapestFlight(from, to, tomorrowStr));
            }
            context.setVariable("flights", flights);
            String destination1 = top4ArrivalCities.get(0);
            String destination2 = top4ArrivalCities.get(1);
            String destination3 = top4ArrivalCities.get(2);
            String destination4 = top4ArrivalCities.get(3);
            int randomNum1 = new Random().nextInt(3) + 1; // 生成 1~3 的随机数
            int randomNum2 = new Random().nextInt(3) + 1;
            int randomNum3 = new Random().nextInt(3) + 1;
            int randomNum4 = new Random().nextInt(3) + 1;
            context.setVariable("Destination1Num", destination1 + randomNum1);
            context.setVariable("Destination2Num", destination2 + randomNum2);
            context.setVariable("Destination3Num", destination3 + randomNum3);
            context.setVariable("Destination4Num", destination4 + randomNum4);
            context.setVariable("Destination1", destination1);
            context.setVariable("Destination2", destination2);
            context.setVariable("Destination3", destination3);
            context.setVariable("Destination4", destination4);
            if(service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(0),tomorrowStr) == null){
                context.setVariable("price1", "暂无价格");
            }else{
                context.setVariable("price1", "¥"+service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(0),tomorrowStr).getEconomy_price()+" 起");
            }
            if(service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(1),tomorrowStr) == null){
                context.setVariable("price2", "暂无价格");
            }else{
                context.setVariable("price2", "¥"+service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(1),tomorrowStr).getEconomy_price()+" 起");
            }
            if(service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(2),tomorrowStr) == null){
                context.setVariable("price3", "暂无价格");
            }else {
                context.setVariable("price3", "¥"+service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(2),tomorrowStr).getEconomy_price()+" 起");
            }
            if(service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(3),tomorrowStr) == null){
                context.setVariable("price4", "暂无价格");
            }else {
                context.setVariable("price4", "¥"+service.searchCheapestFlight(user.getCity(),top4DepartureCities.get(3),tomorrowStr).getEconomy_price()+" 起");
            }
            context.setVariable("user", user);
            // 图片是否存在判断
            String imagePath = getServletContext().getRealPath("/static/images/" + user.getU_id() + ".jpg");
            File imageFile = new File(imagePath);
            boolean imageExists = imageFile.exists();
            context.setVariable("imageExists", imageExists);
            ThymeleafUtil.process("user_index1.html", context, resp.getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
